package com.ruoyi.web.controller.zhishiku;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.FileVersion;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.service.FileService;
import com.ruoyi.system.service.FileVersionService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

@RestController
@AllArgsConstructor
@RequestMapping("/zhishiku/fileVersion")
@ApiOperation("")
public class FileVersionController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(FileVersionController.class);
    final private FileVersionService fileVersionService;

    final private FileService fileService;


    /**
     * 获取当前文件版本列表
     */
    @PostMapping("/list")
    @ApiOperation("查询文件列表")
    public TableDataInfo list(@RequestBody FileVersion fileVersion)
    {
        startPage();
        return getDataTable(fileVersionService.selectFileVersions(fileVersion));
    }

    /**
     * 在线编辑器回调操作
     */
    @ApiOperation("更新文件版本")
    @RequestMapping(path = "/editCallBack", method = {RequestMethod.POST, RequestMethod.GET})
    public void editCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
        String body = scanner.hasNext() ? scanner.next() : "";
        JSONObject jsonObj = JSONObject.parseObject(body);

        String userId = request.getParameter("userId");
        String fileId = request.getParameter("fileId");


        log.info("在线编辑器回调参数：{}", jsonObj);

        if ((Integer) jsonObj.get("status") == 2) {
            String downUrl = (String) jsonObj.get("url"); //保存变更后文件
            String changeUrl = (String) jsonObj.get("changesurl"); //保存文件的修改记录
            String lastsave = (String) jsonObj.get("lastsave");

            try {
                fileService.saveChange(downUrl, changeUrl, fileId, userId, lastsave);
            } catch (Exception e) {
                log.info("保存回调文件出错：{}", e.getMessage());
            }
        }

        writer.write("{\"error\":0}");
    }


}
